package queries;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import connect.DBConnectionUtil;

public class Query1 extends JFrame{
	public Query1(){
		this.setBounds(300,240,500,400);
		this.setLayout(null);
		
		JLabel label0 = new JLabel("Enter new patient information");
		label0.setBounds(200, 10, 300, 30);
		this.add(label0);
		JLabel label1 = new JLabel("Pid:");
		JTextField pid = new JTextField();
		label1.setBounds(100, 50, 100, 30);
		pid.setBounds(200, 50, 200, 30);
		this.add(label1);
		this.add(pid);
		JLabel label2 = new JLabel("Pname");
		JTextField pname = new JTextField();
		label2.setBounds(100, 100, 100, 30);
		pname.setBounds(200, 100, 200, 30);
		this.add(label2);
		this.add(pname);
		JLabel label3 = new JLabel("Address");
		JTextField address = new JTextField();
		label3.setBounds(100, 150, 100, 30);
		address.setBounds(200, 150, 200, 30);
		this.add(label3);
		this.add(address);
		
		JLabel label4 = new JLabel("Phone");
		JTextField phone = new JTextField();
		label4.setBounds(100, 200, 100, 30);
		phone.setBounds(200, 200, 200, 30);
		this.add(label4);
		this.add(phone);
		
		
		JButton insert = new JButton("Insert");
		insert.setBounds(200, 250, 100, 30);
		this.add(insert);
		this.setTitle("Query1:Add Patient");
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		this.setVisible(true);
		insert.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					try{
						Integer.parseInt(pid.getText());
					}catch(Exception e){
						JOptionPane.showMessageDialog(null, "Pid is illegal!");
					}
					// 1.connect database
					Class.forName(DBConnectionUtil.DBDRIVER).newInstance();
					Connection con = DBConnectionUtil.getConnection();
					if(con!=null){
						System.out.println("Connect database successfully!");
					}
					// 2.query code
					PreparedStatement ps = con
							.prepareStatement("INSERT INTO Patient(pid, pname, address, phone) VALUES (?,?,?,?)");
					ps.setString(1, pid.getText());
					ps.setString(2, pname.getText());
					ps.setString(3, address.getText());
					ps.setString(4, phone.getText());
					ps.executeQuery();
					ps.close();
					JOptionPane.showMessageDialog(null, "Insert Patient Info Successfully!");
				} catch (Exception e) {
					JOptionPane.showMessageDialog(null, "Pid already exsits!");
				}
			}
			
		});
	}
}
